//
//  UICollectionView+Extensions.m
//  mobile
//
//  Created by Demi on 10/03/2017.
//  Copyright © 2017 azazie. All rights reserved.
//

#import "UICollectionView+Extensions.h"
#import <objc/runtime.h>

@implementation UICollectionView (Extensions)

+ (instancetype)horizontalFlowLayoutCollectionViewWithCellClass:(Class)cellClass {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    UICollectionView *collectionView = [[self alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    BaseCollectionViewDelegateProxy *delegateProxy = [[BaseCollectionViewDelegateProxy alloc] initWithCellClass:cellClass collectionView:collectionView];
    collectionView.delegateProxy = delegateProxy;
    return collectionView;
}

+ (instancetype)normalFlowLayoutCollectionViewWithCellClass:(Class)cellClass {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    UICollectionView *collectionView = [[self alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    BaseCollectionViewDelegateProxy *delegateProxy = [[BaseCollectionViewDelegateProxy alloc] initWithCellClass:cellClass collectionView:collectionView];
    collectionView.delegateProxy = delegateProxy;
    return collectionView;
}

- (UICollectionViewFlowLayout *)flowLayout
{
    return (UICollectionViewFlowLayout *)self.collectionViewLayout;
}

- (RACSignal<NSNumber *> *)didSelectSignal
{
    return [[self.delegateProxy rac_signalForSelector:@selector(collectionView:didSelectItemAtIndexPath:) fromProtocol:@protocol(UICollectionViewDelegate)] map:^(RACTuple *tuple){
        NSIndexPath *ip = tuple.second;
        return @(ip.item);
    }];
}

#pragma mark - getter / setter

- (void)setDelegateProxy:(BaseCollectionViewDelegateProxy *)delegateProxy
{
    objc_setAssociatedObject(self, @selector(delegateProxy), delegateProxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BaseCollectionViewDelegateProxy *)delegateProxy
{
    return objc_getAssociatedObject(self, _cmd);
}

@end
